package top.xzxsrq.fileviewutils.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.xzxsrq.common.utils.FileUtilsZX;
import top.xzxsrq.common.utils.StringUtilsZX;
import top.xzxsrq.fileviewutils.FileViewUtilsApplication;
import top.xzxsrq.fileviewutils.entity.SysUser;
import top.xzxsrq.fileviewutils.entity.SysUserWithRole;
import top.xzxsrq.fileviewutils.enums.AuthEnum;
import top.xzxsrq.fileviewutils.exception.BusinessException;
import top.xzxsrq.fileviewutils.mapper.SysUserMapper;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class UserDetailsServiceImpl implements UserDetailsService, CommandLineRunner {
    @Autowired
    private PasswordEncoder passwordEncoder;
    public static String adminUserName;
    public static String adminPassword;
    public static String adminUserSysConfig;

    @Value("${adminUser.username}")
    public void setAdminUserName(String adminUserName) {
        UserDetailsServiceImpl.adminUserName = adminUserName;
    }

    @Value("${adminUser.password}")
    public void setAdminPassword(String adminPassword) {
        UserDetailsServiceImpl.adminPassword = adminPassword;
    }

    @Override
    public void run(String... args) throws Exception {
        String s = FileViewUtilsApplication.projectDir + "/config/userSysConfig.json";
        File file = new File(s);
        if (!file.exists()) {
            return;
        }
        String readFileToString = FileUtilsZX.readFileToString(file, StandardCharsets.UTF_8);
        UserDetailsServiceImpl.adminUserSysConfig = readFileToString;
    }

    public static void updateAdminUserSysConfig(String userSysConfig) {
        String s = FileViewUtilsApplication.projectDir + "/config/userSysConfig.json";
        try {
            FileUtilsZX.createFile(s);
            FileUtilsZX.write(new File(s), userSysConfig, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        UserDetailsServiceImpl.adminUserSysConfig = userSysConfig;
    }

    public static void main(String[] args) {
        updateAdminUserSysConfig("{\"test\": \"6666\"}");
    }

    @Autowired
    private SysUserMapper sysUserMapper;
    public final static String INIT_ADMIN_ID = "1";
    public final static String INIT_ADMIN_ROLE_NAME = "initAdmin";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtilsZX.isEmpty(username)) {
            throw new BusinessException("用户不能为空");
        }
        SysUserWithRole sysUserWithRole = new SysUserWithRole();
        if (adminUserName.equals(username)) { // 这是admin用户
            sysUserWithRole.setUserId(INIT_ADMIN_ID);
            sysUserWithRole.setUsername(username);
            sysUserWithRole.setPassword(passwordEncoder.encode(adminPassword));
            sysUserWithRole.setRoleName(INIT_ADMIN_ROLE_NAME);
            sysUserWithRole.setAuths(AuthEnum.getAllAuth());
//            sysUserWithRole.setUserSysConfig(adminUserSysConfig);
        } else {
            SysUser user = new LambdaQueryChainWrapper<>(sysUserMapper)
                    .eq(SysUser::getUsername, username)
                    .one();
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            BeanUtils.copyProperties(user, sysUserWithRole);
        }
        return sysUserWithRole;
    }

}
